/**
 *
 * @author  Timothy Prinzing
 * @version 1.21 01/23/03
 *
 * Control component
 * This class receives inputs, and initiates a response making calls in the
 * model objects.
 */
package br.unb.graphics;

import br.unb.graphics.help.OpenBrowser;
import br.unb.graphics.inference.InferenceDataImporter;
import java.io.File;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JToolBar;

import br.unb.core.dispatcher.TrafficDispatcher;
import br.unb.core.manager.Manager;
import br.unb.utils.Console;
import br.unb.utils.LogFile;
import br.unb.utils.Resource;
import br.unb.utils.Path;
import javax.swing.JOptionPane;

public class ControlComponent extends JPanel {

    //TODO Constants, (move to another file, labels)
    public static final String openInferenceAction = "openInference";
    public static final String openQosAction = "openQos";
    public static final String newAction = "new";
    public static final String exitAction = "exit";
    public static final String addAction = "add";
    public static final String chatAction = "chat";
    public static final String startAction = "start";
    public static final String startRealAction = "startReal";
    public static final String stopAction = "stop";
    public static final String deleteAction = "delete";
    public static final String synchronizeAction = "synchronize";
    public static final String helpAction = "help";
    public static final String aboutAction = "about";
    public static final String portuguesAction = "portugues";
    public static final String englishAction = "english";
    private OpenBrowser browser;
    private boolean[] isOnScreen;
    private String[] isOnScreenName;
    private InterfaceFactory ifactory;
    private JMenuBar menubar;
    private JToolBar toolbar;
    private static NewTrafficPanel ntp = NewTrafficPanel.getInstance();
    private static ControlComponent INSTANCE = new ControlComponent();

    public static ControlComponent getInstance() {
        return INSTANCE;
    }

    private ControlComponent() {
        super(true);

        // Force SwingSet to come up in the Cross Platform L&F
        try {
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            // If you want the System L&F instead, comment out the above line and
            // uncomment the following:
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
            Console.printError(
                    Resource.getString("ERROR_LOADING_LOOK_AND_FELL_") + exc);
        }

        this.setBorder(BorderFactory.createEtchedBorder());
        this.setLayout(new BorderLayout());
        //ifactory = new InterfaceFactory(Resource.ControlComponent, getActions());
        ifactory = new InterfaceFactory(Resource.ControlComponent, actions);
        menubar = ifactory.createMenubar();
        this.add(BorderLayout.NORTH, menubar);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        //panel.add(BorderLayout.NORTH, ifactory.createToolbar());
        this.add(BorderLayout.CENTER, panel);
    }

    /**
     * Fetch the list of actions supported by this
     * editor.  It is implemented to return the list
     * of actions supported by the embedded JTextComponent
     * augmented with the actions defined locally.
     */
    public Action[] getActions() {
        //return TextAction.augmentList(new JTextArea().getActions(), defaultActions);
        return actions;
    }

    /**
     * To shutdown when run as an application.  This is a
     * fairly lame implementation.   A more self-respecting
     * implementation would at least check to see if a save
     * was needed.
     */
    protected static final class AppCloser extends WindowAdapter {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }

    /**
     * Find the hosting frame, for the file-chooser dialog.
     */
    protected Frame getFrame() {
        for (Container p = getParent(); p != null; p = p.getParent()) {
            if (p instanceof Frame) {
                return (Frame) p;
            }
        }
        return null;
    }

    protected Container getToolbar() {
        return toolbar;
    }

    protected JMenuBar getMenubar() {
        return menubar;
    }
    
    /************************* action implementations *****************************/
    /**
     * Actions defined by the ControlComponent class
     */
    private Action[] actions = {
        new NewAction(),
        new OpenInferenceAction(),
        new OpenQosAction(),
        new ExitAction(),
        new AddAction(),
        new SynchronizeAction(),
        new ChatAction()
    };

    /*********************************************************************/
    /*********************         ACTIONS           *********************/
    /*********************************************************************/
    public static class OpenInferenceAction extends AbstractAction {

        OpenInferenceAction() {
            super(openInferenceAction);
        }

        public void actionPerformed(ActionEvent e) {
            //TODO review open file action (too clumbersome)
            JFileChooser fc = new JFileChooser(Path.getLogDir());
            fc.setFileFilter(LogFile.Type.RECEIVER.getFileFilter());
            fc.setDialogTitle("Open Inference File");

            int o = fc.showOpenDialog(null);
            switch (o) {
                case JFileChooser.APPROVE_OPTION: {
                    File inferencefile = (File) fc.getSelectedFile();
                    if (inferencefile != null) {
                        InferenceDataImporter dataimporter = new InferenceDataImporter(inferencefile);
                        dataimporter.setSize(InferenceDataImporter.firstPaneDimension);
                        dataimporter.setResizable(false);
                        dataimporter.setVisible(true);
                        GraphicInterface.getInstance().showInferencePanel();
                    } else {
                        Console.printError(Resource.getString("SELECT_VALID_FILE"));
                    }
                }
                break;
                case JFileChooser.CANCEL_OPTION: {
                    Console.printError(Resource.getString("FILE_SELECTION_CANCELED"));
                }
                break;
            }
        }
    }

    class OpenQosAction extends AbstractAction {

        OpenQosAction() {
            super(openQosAction);
        }

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser(Path.getLogDir());
            fc.setFileFilter(LogFile.Type.RECEIVER.getFileFilter());
            fc.setDialogTitle("Open Qos File");

            int o = fc.showOpenDialog(null);
            switch (o) {
                case JFileChooser.APPROVE_OPTION: {
                    File qosFile = fc.getSelectedFile();
                    File l = new File(qosFile.getName());
                    if (qosFile != null) {
                        GraphicInterface.getInstance().showQosPanel();
                        TrafficDispatcher.qosController.loadValuesFromFile(qosFile);
                    } else {
                        Console.printError(Resource.getString("SELECT_VALID_FILE"));
                    }
                }
                break;
                case JFileChooser.CANCEL_OPTION: {
                    Console.printError(Resource.getString("FILE_SELECTION_CANCELED"));
                }
                break;
            }
        }
    }

    class NewAction extends AbstractAction {

        NewAction() {
            super(newAction);
        }

        public void actionPerformed(ActionEvent e) {
            Manager.getInstance().stopAllTraffic();
            GraphicInterface.getInstance().resetTabs();
            Runtime.getRuntime().gc();
        }
    }

    /**
     * Really lame implementation of an exit command
     */
    //TODO review implementation of this exit actions
    class ExitAction extends AbstractAction {

        ExitAction() {
            super(exitAction);
        }

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    class AddAction extends AbstractAction {

        AddAction() {
            super(addAction);
        }

        public void actionPerformed(ActionEvent e) {
            GraphicInterface.getInstance().showNewTrafficPanel();
        }
    }

    class SynchronizeAction extends AbstractAction {

        SynchronizeAction() {
            super(synchronizeAction);
        }

        public void actionPerformed(ActionEvent e) {
            GraphicInterface.getInstance().showSyncPanel();
        }
    }

    class ChatAction extends AbstractAction {

        ChatAction() {
            super(chatAction);
        }

        public void actionPerformed(ActionEvent e) {
            GraphicInterface.getInstance().showChatPanel();
        }
    }

    class HelpAction extends AbstractAction {

        HelpAction() {
            super(helpAction);
        }

        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < 10; i++) {
                if (isOnScreen[i]) {
                    if (GraphicInterface.getInstance().tabs.getComponent(i) != null) {
                        if (GraphicInterface.getInstance().tabs.getComponent(i).isShowing()) {
                            if (isOnScreenName[i] != null) {
                                browser.OpenHelp(isOnScreenName[i] + "/" + isOnScreenName[i] + ".html");
                            } else {
                                JOptionPane.showMessageDialog(null, "can't find help to this tab");
                            }
                        }
                    }
                }
            }
        }
    }

    class PortuguesAction extends AbstractAction {

        PortuguesAction() {
            super(portuguesAction);
        }

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "portugues");
        }
    }

    class EnglishAction extends AbstractAction {

        EnglishAction() {
            super(englishAction);
        }

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "english");
        }
    }
}
